<template>
  <div id="locationMapDialog" v-show="visible">
    <div id="containerStyle"></div>
    <div class="dialogStyle">
      <div id="map-container" class="mapStyle"/>
      <el-row>
        <el-col :span="12">
          <el-input id="addressSearch" v-model="addressText" class="inputTextStyle" placeholder="搜索地址"
                    style="margin-left: 20px"
          />
        </el-col>
        <el-col :span="24">
          <div style="margin-top: 5px;margin-bottom: 5px;margin-right: 20px;float: right;">
            <el-button type="primary" :disabled="disableConfirmButton" @click="handleConfirm">确定</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { hasText, removeSubStringList } from '@/api/system/commonUtils'
import markerIcon from '@/assets/image/markerIcon.png'

export default {
  name: 'addressSearch',
  props: {
    // 是否可见
    visible: {
      type: Boolean,
      default: false
    },
    // 城市编码, 用于限定搜索范围
    cityCode: {
      type: String | Number,
      default: '全国'
    },
    // 地图中心点与标记位置
    center: {
      type: Array,
      default: () => [120.028666000000000, 30.241042000000000]
    },
    // 修改时传入的地址
    address: {
      type: String,
      default: ''
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.resetMap()
      }
    },

    center(newValue) {
      this.defaultCenter = newValue
      this.locationMapContainer.setCenter(this.defaultCenter)
    }
  },
  data() {
    return {
      defaultZoom: 14,
      searchLocationZoom: 14,
      locationMapContainer: undefined,
      addressMarker: undefined,
      addressText: undefined,
      disableConfirmButton: true,
      autocomplete: undefined,
      defaultCenter: [120.028666000000000, 30.241042000000000],
      geocoder: undefined
    }
  },
  mounted() {
    this.initMap()
    document.documentElement.style.overflowY = 'hidden'
    // let layer = document.getElementById('containerStyle')
    // layer.style.width = document.body.clientWidth + 'px'
    // layer.style.height = document.body.clientHeight + 'px'
  },
  methods: {
    initMap() {
      // 初始化地图
      this.locationMapContainer = new AMap.Map('map-container', {
        zoom: this.defaultZoom,
        resizeEnable: true,
        center: this.defaultCenter
      })

      // 添加标记
      this.addressMarker = new AMap.Marker({
        map: this.locationMapContainer,
        position: this.defaultCenter,
        // content: `<img src="${markerIcon}" alt="">`,
        icon: markerIcon,
        draggable: true
      })

      // 添加点标记拖拽移动结束事件
      AMap.event.addListener(this.addressMarker, 'dragend', (e) => {
        let markerPosition = this.addressMarker.getPosition()
        let center = [markerPosition.R, markerPosition.Q]
        // 重置地图中心点和标记位置, 标记设置动画, 逆地址解析
        this.locationMapContainer.setCenter(center)
        this.addressMarker.setAnimation('AMAP_ANIMATION_DROP')
        this.reGeoCode(center)
      })

      // 添加地址自动填充
      AMap.plugin(['AMap.Autocomplete'], () => {
        let autoOptions = {
          city: '全国',
          input: 'addressSearch'
        }

        this.autocomplete = new AMap.Autocomplete(autoOptions)
        // 强制限制城市
        this.autocomplete.setCityLimit(true)

        //注册监听，当选中某条记录时会触发
        AMap.event.addListener(this.autocomplete, 'select', e => {
          if (e.poi.location.Q) {
            let center = [e.poi.location.R, e.poi.location.Q]
            this.addressText = e.poi.name
            // 标记重定位
            this.addressMarker.setPosition(center)
            this.addressMarker.setAnimation('AMAP_ANIMATION_DROP')

            this.locationMapContainer.setCenter(center)
            this.locationMapContainer.setZoom(this.searchLocationZoom)
            this.disableConfirmButton = false
          } else {
            this.disableConfirmButton = true
          }
        })
      })

      // 地理编码与逆地理编码服务
      this.geocoder = new AMap.Geocoder({
        city: '全国',
        radius: 1000 //范围(米)
      })
    },

    resetMap() {
      this.addressText = null
      this.disableConfirmButton = true
      this.addressMarker.setPosition(this.center)
      this.locationMapContainer.setCenter(this.center)
      this.locationMapContainer.setZoom(this.defaultZoom)
      // 显示组件时限定搜索城市
      this.autocomplete.setCity(this.cityCode)

      // 若是修改地址, 则有值传进来
      if (hasText(this.address)) {
        this.addressText = this.address
        this.disableConfirmButton = false
      }
    },

    // 自定义'returnAddress'事件, 在点击确认或取消后向父组件传递数据
    handleConfirm() {
      this.$emit('setVisible', false)
      this.$emit('returnAddress', {
        status: 200,
        address: this.addressText,
        position: JSON.parse(JSON.stringify(this.addressMarker.getPosition()))
      })
    },
    handleCancel() {
      this.$emit('setVisible', false)
      this.$emit('returnAddress', { status: 400 })
      document.documentElement.style.overflowY = 'visible'
    },

    // 逆地址转换(通过坐标查询地址)
    reGeoCode(center) {
      this.geocoder.getAddress(center, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          let regeocode = result.regeocode
          let addressComponent = regeocode.addressComponent
          if (addressComponent) {
            let district = [addressComponent.province, addressComponent.city, addressComponent.district]
            let formattedAddress = regeocode.formattedAddress
            // console.log(JSON.stringify(district))
            // console.log(formattedAddress)
            // console.log(removeSubStringList(formattedAddress, district))
            this.addressText = removeSubStringList(formattedAddress, district)
            this.disableConfirmButton = false
          }
        }
      })
    }
  }
}
</script>
<style>
.amap-sug-result {
  /*提示列表置于前侧*/
  z-index: 9999
}
</style>


<style scoped>
/*遮罩层样式*/
#containerStyle {
  opacity: .5;
  background-color: black;
  z-index: 3000;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: auto;
  margin: 0;
}

/*地图div样式*/
.mapStyle {
  margin: 20px;
  height: 75%;
  border: #938d80 1px solid;
}

/*弹出框样式*/
.dialogStyle {
  height: calc(80vh);
  width: calc(50vw);
  /*height: 80%;*/
  /*width: 50%;*/
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 4000;
  background-color: white;
  border-radius: 3px;
}

.inputTextStyle {
  margin-top: 10px;
}
</style>
